package com.example.oauthauthorizationserver.business.service;

import com.example.oauthauthorizationserver.business.bean.UserBean;
import com.example.oauthauthorizationserver.business.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

@Service
public class SpringDataUserDetailsService implements UserDetailsService {

    @Autowired
    UserDao userDao;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 将来连接数据库根据账号查询用户信息
        UserBean bean = userDao.getUserByUsername(username);
        System.out.println(bean);
        if (bean == null) {
            return null;
        }
        System.err.println("au");
        // 查询当前数据库的用户资源权限
        List<String> authorize = userDao.getAuthorize(bean.getId());
        String[] authorizeArr = new String[authorize.size()];
        authorize.toArray(authorizeArr);
        System.out.println(Arrays.toString(authorizeArr));


        // 添加权限
        return User.withUsername(bean.getUserName())
                .password(bean.getPassword())
                .authorities(authorizeArr)
                .roles("ADMIN") // roles() 方法会覆盖之前通过 authorities() 设置的所有权限。
                .build();
    }
    /*
    * .roles("ADMIN", "USER")
        // 等价于：
        .authorities("ROLE_ADMIN", "ROLE_USER")
    * */
}
